Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Function returning "undefined" while trying to query database in node.js

This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!

var funcs = require('./index.js');
var connected = require('./database')

query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)


function execute_rows(query){
 con = connected();
 con.query(query, function(err, result, fields) {
     if (err) {
         return console.log(err);
     }
     console.log(result) //Displays correct results
     return result; // Returns undefined to calling function
 })
 con.end();
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Harshith

Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.

The problem with your function is your not actually returning the result "on time". You need to return a promise to get the result from your function.

This could be a little hard to understand when you're new in JS. Your function should be something like this:

function execute_rows(query){
 con = connected();
 return new Promise((resolve, reject) => {
     con.query(query, function(err, result, fields) {
         if (err) {
             // Returning the error
             reject(err);
             con.end();
         }

         resolve(result);
         con.end();
     });
 });
}

Now, when you call you call your function, you have two options:

  1. Use async/await
  2. Still using promises (callback-driven)

Calling your function:

const dbResult = await execute_rows(query);

or

execute_rows(query).then(result => {
    // Get the result
    console.log('result:', result);
}).catch(error => {
    // Get the error
    console.log('error:', error);
});

Please, read about promises and async/await pattern! Links:

Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda